use chrono::{DateTime, Local, TimeZone, Utc};
use tauri::command;
use crate::types::ApiResponse;

#[command]
pub fn timestamp_to_datetime(timestamp: i64, is_milliseconds: bool) -> ApiResponse {
    let (seconds, milliseconds) = if is_milliseconds {
        (timestamp / 1000, (timestamp % 1000) as u32)
    } else {
        (timestamp, 0)
    };

    match Utc.timestamp_opt(seconds, milliseconds * 1_000_000) {
        chrono::LocalResult::Single(datetime) => {
            let local_datetime: DateTime<Local> = DateTime::from(datetime);
            let format_str = if is_milliseconds {
                "%Y-%m-%d %H:%M:%S%.3f"
            } else {
                "%Y-%m-%d %H:%M:%S"
            };
            ApiResponse::success(local_datetime.format(format_str).to_string())
        },
        _ => ApiResponse::error("无效的时间戳".to_string())
    }
}

#[command]
pub fn datetime_to_timestamp(datetime_str: String, is_milliseconds: bool, timezone: String) -> ApiResponse {
    println!("[DEBUG] 输入参数:");
    println!("  - 时间字符串: {}", datetime_str);
    println!("  - 时区: {}", timezone);
    println!("  - 是否毫秒: {}", is_milliseconds);

    // 尝试多种时间格式
    let formats = [
        "%Y-%m-%d %H:%M:%S%.3f",  // 2024-03-14 15:30:00.123
        "%Y-%m-%d %H:%M:%S",      // 2024-03-14 15:30:00
        "%Y-%m-%d %H:%M",         // 2024-03-14 15:30
        "%Y-%m-%d",               // 2024-03-14
        "%Y/%m/%d %H:%M:%S%.3f",  // 2024/03/14 15:30:00.123
        "%Y/%m/%d %H:%M:%S",      // 2024/03/14 15:30:00
        "%Y/%m/%d %H:%M",         // 2024/03/14 15:30
        "%Y/%m/%d",               // 2024/03/14
    ];

    for format in formats.iter() {
        let datetime_with_tz = format!("{} {}", datetime_str, timezone);
        println!("[DEBUG] 尝试解析格式: {}", format);
        println!("  - 完整字符串: {}", datetime_with_tz);
        
        if let Ok(datetime) = DateTime::parse_from_str(&datetime_with_tz, &format!("{} %z", format)) {
            let timestamp = datetime.timestamp();
            let result = if is_milliseconds {
                // 获取毫秒部分
                let milliseconds = datetime.timestamp_subsec_millis() as i64;
                timestamp * 1000 + milliseconds
            } else {
                timestamp
            };
            println!("[DEBUG] 解析成功:");
            println!("  - 时间戳: {}", result);
            println!("  - 格式化时间: {}", datetime.format("%Y-%m-%d %H:%M:%S%.3f %z"));
            return ApiResponse::success(result.to_string());
        } else {
            println!("[DEBUG] 格式不匹配");
        }
    }

    println!("[DEBUG] 所有格式都匹配失败");
    ApiResponse::error(format!("无效的时间格式，支持的格式有：\nYYYY-MM-DD HH:mm:ss.SSS\nYYYY-MM-DD HH:mm:ss\nYYYY-MM-DD HH:mm\nYYYY-MM-DD\nYYYY/MM/DD HH:mm:ss.SSS\nYYYY/MM/DD HH:mm:ss\nYYYY/MM/DD HH:mm\nYYYY/MM/DD"))
} 